package com.lin.nio.channel.multiplexing;

import com.lin.nio.utils.ByteBufferUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class WriterClient {
    public static void main(String[] args) throws IOException {

        SocketChannel scClient = SocketChannel.open();
        scClient.connect(new InetSocketAddress(1122));

        Selector selector = Selector.open();
        scClient.configureBlocking(false);
        ByteBuffer buffer = ByteBuffer.allocate(16);
        scClient.register(selector, SelectionKey.OP_READ, buffer);

        while (true) {
            selector.select();

//            System.out.println("客户端读事件");

            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();

                ByteBuffer dst = (ByteBuffer) key.attachment();
                scClient.read(dst);
                if (dst.limit() == dst.position()) { // 客户端的消息buffer需要扩容
                    dst.flip();
                    ByteBuffer newBuffer = ByteBuffer.allocate(dst.capacity() * 2);
                    newBuffer.put(dst);
                    key.attach(newBuffer);
                } else
                    System.out.println("收到服务端消息：" + dst.position());
            }
        }
    }
}
